import 'package:flutter/cupertino.dart';
import 'package:flutter_chat/common/constant/constants.dart';
import 'package:flutter_chat/common/entity/entitys.dart';
import 'package:flutter_chat/common/store/stores.dart';
import 'package:flutter_chat/common/utils/utils.dart';
import 'package:flutter_chat/common/widget/widgets.dart';
import 'package:get/get.dart';

import 'state.dart';

class LoginLogic extends CustomGetxController {
  final LoginState state = LoginState();
  final formKey = GlobalKey<FormState>();
  final UserStore userStore = UserStore.to;

  /// 更新登录数据
  updateLoginData(String field, String value) {
    state.loginData = UserLogin(
      username: field == "username" ? value : state.loginData.username,
      password: field == "password" ? value : state.loginData.password,
    );
  }

  /// 登录
  Future<void> onLogin() async {
    if (!formKey.currentState!.validate()) {
      return;
    }
    await LoadingUtil.loadingTryAsync(
      text: "登录中...",
      callback: () async {
        bool isLogin = await userStore.login(
          username: state.loginData.username!,
          password: state.loginData.password!,
        );
        if (isLogin) {
          Get.offAllNamed(RouterName.index);
        }
      },
    );
  }
}
